package cv.vender;

import android.content.Context;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import cv.vender.http.clsHttpFrame;

/**
 * Created by Administrator on 2017/9/2.
 *
 */

public class LocalTradeUtils {

    /**
     * 保存没有发送成功的数据到文件
     * @param trade_data
     */
    public static void SaveHttpTradeDataToFile(String trade_data)
    {
        //System.out.println(trade_data);
        String tradefile=clsPublicPara.HttpTradeFile;
        try {
            FileOutputStream fos = clsPublicPara.activity.openFileOutput(tradefile, Context.MODE_APPEND);
            fos.write(trade_data.getBytes("GBK"));
            fos.write("\r\n".getBytes("GBK"));
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void ReadySendFileHttpTrade()
    {
        //System.out.println(trade_data);
        String tradefile=clsPublicPara.HttpTradeFile;
        if(!new File(clsPublicPara.activity.getFilesDir()+"/"+tradefile).exists())
        {
            System.out.println("没有文件需要发送");
            return;
        }
        try {
            FileInputStream fis = clsPublicPara.activity.openFileInput(tradefile);
            InputStreamReader isp=new InputStreamReader(fis, "GBK");
            BufferedReader br = new BufferedReader(isp);

            String line=null;
            while ((line = br.readLine()) != null)
            {
                //clsHttpFrame.SendOtherDataFrame(line);
                SendLocalTradeToServer(line);
            }
            clsPublicPara.activity.deleteFile(tradefile);

            br.close();
            isp.close();
            fis.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void SendLocalTradeToServer(String line)
    {
        clsHttpFrame.SendHttpTradeFrame(line);
    }

}
